<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">入库红冲记录</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">查询信息</text>
      </view>
      <view class="info-form">
        <view class="form-item">
          <text class="form-label">查询日期</text>
          <picker
            mode="date"
            :value="formData.queryDate"
            @change="handleDateChange"
          >
            <view class="warehouse-picker">
              <text class="warehouse-display">{{ formData.queryDate }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">仓库</text>
          <picker
            mode="selector"
            :range="targetWarehouseOptions"
            range-key="text"
            :value="currentWarehouseIndex"
            @change="handleWarehouseChange"
          >
            <view class="warehouse-picker">
              <text class="warehouse-display">{{
                currentWarehouse ? currentWarehouse.warehouseName : "请选择仓库"
              }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- C. 时间筛选按钮组 -->
    <view class="search-section">
      <view class="section-header">
        <text class="section-title">查询条件</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'today' }"
            @tap="handleTimeChange('today')"
          >
            当日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'week' }"
            @tap="handleTimeChange('week')"
          >
            近7天
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'month' }"
            @tap="handleTimeChange('month')"
          >
            近1个月
          </button>
        </view>
      </view>
    </view>

    <!-- D. 主表数据 -->
    <view class="material-table-section">
      <view class="section-header">
        <text class="section-title">入库冲销单列表</text>
        <view class="statistics-info">
          <text class="stat-item">已查询条目: {{ mainTableData.length }}</text>
        </view>
      </view>
      <view class="table-scroll-container">
        <scroll-view
          class="table-scroll-wrapper"
          scroll-x
          scroll-with-animation
        >
          <view class="table-content">
            <view class="table-row header">
              <text class="header-cell select-col">选择</text>
              <text class="header-cell">创建时间</text>
              <text class="header-cell">创建人</text>
              <text class="header-cell">供应商</text>
              <text class="header-cell">入库类型</text>
              <text class="header-cell">入库单号</text>
            </view>
            <view
              v-for="(item, index) in mainTableData"
              :key="index"
              class="table-row"
              :class="{
                selected: selectedMainRow && selectedMainRow.id === item.id,
              }"
              @click="selectMainRow(item)"
            >
              <view class="table-cell select-col">
                <view class="custom-checkbox" @click.stop="selectMainRow(item)">
                  <view
                    class="checkbox-icon"
                    :class="{
                      'checkbox-checked':
                        selectedMainRow && selectedMainRow.id === item.id,
                    }"
                  >
                    <text
                      v-if="selectedMainRow && selectedMainRow.id === item.id"
                      class="check-mark"
                      >✓</text
                    >
                  </view>
                </view>
              </view>
              <text class="table-cell">{{
                item.ywDate ? dateHelperApi.formateTime(item.ywDate) : "-"
              }}</text>
              <text class="table-cell">{{ item.creator || "-" }}</text>
              <text class="table-cell">{{ item.suppName || "-" }}</text>
              <text class="table-cell">{{ item.inType || "-" }}</text>
              <text class="table-cell">{{ item.mainNo || "-" }}</text>
            </view>
          </view>
        </scroll-view>
        <view class="scroll-hint" :class="{ show: mainTableData.length > 0 }">
          <text class="hint-icon">↔</text>
          横向滑动查看更多
        </view>
      </view>
    </view>

    <!-- E. 明细表数据 -->
    <view class="material-table-section" v-if="selectedMainRow">
      <view class="section-header">
        <text class="section-title">入库明细表</text>
        <view class="statistics-info">
          <text class="stat-item">总重: {{ totalWeight }} KG</text>
          <text class="stat-item">总数量: {{ totalQuantity }}</text>
        </view>
      </view>
      <view class="table-scroll-container">
        <scroll-view
          class="table-scroll-wrapper"
          scroll-x
          scroll-with-animation
        >
          <view class="table-content">
            <view class="table-row header">
              <text class="header-cell">物料编码</text>
              <text class="header-cell">物料名称</text>
              <text class="header-cell">规格</text>
              <text class="header-cell">数量</text>
              <text class="header-cell">重量(KG)</text>
              <text class="header-cell">单价</text>
              <text class="header-cell">金额</text>
            </view>
            <view
              v-for="(item, index) in detailTableData"
              :key="index"
              class="table-row"
            >
              <text class="table-cell">{{
                item.materialCode || item.matCode || "-"
              }}</text>
              <text class="table-cell">{{
                item.materialName || item.matName || "-"
              }}</text>
              <text class="table-cell">{{
                item.specification || item.spec || "-"
              }}</text>
              <text class="table-cell">{{ item.transCount || 0 }}</text>
              <text class="table-cell">{{
                (item.prodCount || item.weight || 0).toFixed(3)
              }}</text>
              <text class="table-cell">{{
                item.prodPrice || item.price || "-"
              }}</text>
              <text class="table-cell">{{
                (
                  (item.prodCount || item.weight || 0) *
                  (item.prodPrice || item.price || 0)
                ).toFixed(2)
              }}</text>
            </view>
          </view>
        </scroll-view>
        <view class="scroll-hint" :class="{ show: detailTableData.length > 0 }">
          <text class="hint-icon">↔</text>
          横向滑动查看更多
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { reverseApi } from "@/api/warehouse/reverse";
import { warehouseApi } from "@/api/warehouse/warehouse";
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";

export default {
  name: "StockInReport",
  data() {
    return {
      // 表单数据
      formData: {
        queryDate: dateHelperApi.getCurrentDate(),
        warehouseCode: "",
        warehouseName: "",
      },

      // 当前仓库信息
      currentWarehouse: {
        warehouseCode: "",
        warehouseName: "请选择仓库",
      },

      // 时间筛选器
      timeFilter: "today",
      // 时间范围
      timeRange: {
        startTime: "",
        endTime: "",
      },

      // 主表数据
      mainTableData: [],
      // 明细表数据
      detailTableData: [],
      // 选中的主表行
      selectedMainRow: null,

      // 加载状态
      loading: false,
      // 仓库选项列表
      targetWarehouseOptions: [],
      // 当前仓库索引
      currentWarehouseIndex: -1,
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 所有明细行总重量
    totalWeight() {
      return this.detailTableData
        .reduce((total, item) => {
          return total + (parseFloat(item.prodCount) || 0);
        }, 0)
        .toFixed(3);
    },
    // 所有明细行总数量
    totalQuantity() {
      return this.detailTableData.reduce((total, item) => {
        return total + (parseInt(item.transCount) || 0);
      }, 0);
    },
  },
  onLoad() {
    this.loadCurrentWarehouse();
    this.loadWarehouseOptions(); // 加载仓库选项
    // 页面加载时初始化时间范围并加载数据
    this.handleTimeChange("today");
    this.$nextTick(() => {
      this.loadMainTableData();
    });
  },
  methods: {
    /* 加载当前仓库 */
    loadCurrentWarehouse() {
      const userConfig = this.$store.state.user.userConfig;
      if (userConfig && userConfig.wmName) {
        this.currentWarehouse = {
          warehouseCode: userConfig.wmCode || "DEFAULT",
          warehouseName: userConfig.wmName,
        };
        this.formData.warehouseCode = this.currentWarehouse.warehouseCode;
        this.formData.warehouseName = this.currentWarehouse.warehouseName;
      }
    },

    /* 加载仓库选项 */
    async loadWarehouseOptions() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          dictType: "wm_name_po",
        };
        const response = await warehouseApi.getWarehouseList(params);
        if (response.code === 0) {
          // 将数据转换为下拉选项格式，根据API返回的字段名称
          this.targetWarehouseOptions = (response.data.list || []).map(
            (item) => ({
              value: item.value,
              text: item.label,
              warehouseName: item.label, // 用于显示
            })
          );
          console.log("目标仓库数据加载成功:", this.targetWarehouseOptions);

          // 如果当前有仓库，设置对应的索引
          if (this.currentWarehouse && this.currentWarehouse.warehouseName) {
            const index = this.targetWarehouseOptions.findIndex(
              (option) =>
                option.warehouseName === this.currentWarehouse.warehouseName
            );
            if (index !== -1) {
              this.currentWarehouseIndex = index;
            }
          }
        }
      } catch (error) {
        console.error("加载仓库选项失败:", error);
      }
    },

    /* 处理仓库选择变化 */
    handleWarehouseChange(e) {
      const index = e.detail.value;
      this.currentWarehouseIndex = index;
      const selectedWarehouse = this.targetWarehouseOptions[index];
      if (selectedWarehouse) {
        this.currentWarehouse = {
          warehouseCode: selectedWarehouse.value,
          warehouseName: selectedWarehouse.warehouseName,
        };
        this.formData.warehouseCode = selectedWarehouse.value;
        this.formData.warehouseName = selectedWarehouse.warehouseName;

        // 重新搜索数据
        this.loadMainTableData();
      }
    },

    /* 处理日期选择 */
    handleDateChange(e) {
      this.formData.queryDate = e.detail.value;
      this.loadMainTableData();
    },

    /* 时间选择处理 */
    handleTimeChange(timeFilter) {
      // 更新时间筛选器
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });

      // 重新加载数据
      this.$nextTick(() => {
        this.loadMainTableData();
      });
    },

    /* 加载主表数据 */
    async loadMainTableData() {
      if (this.loading) return;
      this.loading = true;

      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          inType: "红冲入库",
          warehouseName: this.currentWarehouse.warehouseName || "",
        };

        // 添加时间范围参数
        if (this.timeRange.startTime && this.timeRange.endTime) {
          params.ywDate = [this.timeRange.startTime, this.timeRange.endTime];
        }

        console.log("查询主表参数:", params);
        const response = await reverseApi.getPoStockInMainPage(params);
        console.log("主表数据响应:", response);

        if (response.code === 0) {
          this.mainTableData = response.data.list || [];
          // 清空明细数据和选择
          this.detailTableData = [];
          this.selectedMainRow = null;
        } else {
          uni.showToast({
            title: response.message || "加载主表数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载主表数据失败:", error);
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      this.loading = false;
    },

    /* 选择主表行 */
    async selectMainRow(row) {
      console.log("选择主表行:", row);
      if (this.selectedMainRow && this.selectedMainRow.id === row.id) {
        console.log("点击已选中的行，取消选择:", row);
        // 如果点击已选中的行，则取消选择
        this.selectedMainRow = null;
        this.detailTableData = [];
        return;
      }

      console.log("选择新行，ID:", row.id);
      this.selectedMainRow = row;

      // 加载对应的明细数据
      console.log("开始加载明细数据...");
      await this.loadDetailTableData(row.id);
      console.log("明细数据加载完成，数据量:", this.detailTableData.length);
    },

    /* 加载明细表数据 */
    async loadDetailTableData(mainId) {
      if (this.loading) return;
      this.loading = true;

      try {
        console.log("开始加载明细表数据，主表ID:", mainId);
        const params = {
          pageNo: 1,
          pageSize: 100,
          mainId: mainId,
        };
        const response = await reverseApi.getPoStockIn(params);
        console.log("明细表数据响应:", response);
        console.log("响应数据结构:", JSON.stringify(response, null, 2));

        if (response.code === 0) {
          // 检查数据结构，可能是 response.data 直接是数组，或者 response.data.list 是数组
          let detailData = [];
          if (Array.isArray(response.data)) {
            detailData = response.data;
          } else if (response.data && Array.isArray(response.data.list)) {
            detailData = response.data.list;
          } else if (response.data && response.data.records) {
            detailData = response.data.records;
          } else if (response.data) {
            // 如果data是对象，尝试从中提取数组
            const keys = Object.keys(response.data);
            console.log("响应data的键:", keys);
            for (let key of keys) {
              if (Array.isArray(response.data[key])) {
                detailData = response.data[key];
                console.log("找到数组数据在键:", key);
                break;
              }
            }
            if (detailData.length === 0) {
              console.warn("未找到明细数据数组，尝试将整个data作为单个记录");
              detailData = [response.data]; // 作为单个记录
            }
          } else {
            detailData = [];
            console.warn("未找到明细数据，数据结构:", response.data);
          }

          // 确保所有项目都有必要的字段
          this.detailTableData = detailData.map((item) => ({
            ...item,
            transCount: item.transCount || item.quantity || 0,
            prodCount: item.prodCount || item.weight || item.quantity || 0,
            prodPrice: item.prodPrice || item.price || 0,
            materialCode: item.materialCode || item.matCode || "",
            materialName: item.materialName || item.matName || "",
            specification: item.specification || item.spec || "",
          }));

          console.log("处理后的明细表数据:", this.detailTableData);

          // 如果没有数据，显示提示
          if (this.detailTableData.length === 0) {
            uni.showToast({
              title: "该入库单暂无明细数据",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.message || "加载明细数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载明细数据失败:", error);
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      this.loading = false;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/smart/scss/create.scss";
</style>
